package com.alangyun.remind.utils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Utility {

	public static final String DATE_FORMAT = "yyyy-MM-dd";
	public static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
	
	public static final String[] SUDOKU_STAR_REMARKS = new String[] {
			"不及格",
			"一般",
			"一般",
			"一般",
			"良好",
			"良好",
			"优秀",
			"优秀",
			"卓越"
	};
	public static final int SUDOKU_CAPICITY =9;

	public static boolean isNumber(String str) {
        if (str.length() == 0) {
            return false;
        }
        int sz = str.length();
        boolean hasExp = false;
        boolean hasDecPoint = false;
        boolean allowSigns = false;
        boolean foundDigit = false;
        // deal with any possible sign up front
        int start = (str.charAt(0) == '-') ? 1 : 0;
        if (sz > start + 1) {
            if (str.charAt(start) == '0' && str.charAt(start + 1) == 'x') {
                int i = start + 2;
                if (i == sz) {
                    return false; // str == "0x"
                }
                // checking hex (it can't be anything else)
                for (; i < str.length(); i++) {
                    char ch = str.charAt(i);
                    if ((ch < '0' || ch > '9')
                            && (ch < 'a' || ch > 'f')
                            && (ch < 'A' || ch > 'F')) {
                        return false;
                    }
                }
                return true;
            }
        }
        sz--; // don't want to loop to the last char, check it afterwords
        // for type qualifiers
        int i = start;
        // loop to the next to last char or to the last char if we need another digit to
        // make a valid number (e.g. chars[0..5] = "1234E")
        while (i < sz || (i < sz + 1 && allowSigns && !foundDigit)) {
            char ch = str.charAt(i);
            if (ch >= '0' && ch <= '9') {
                foundDigit = true;
                allowSigns = false;

            } else if (ch == '.') {
                if (hasDecPoint || hasExp) {
                    // two decimal points or dec in exponent
                    return false;
                }
                hasDecPoint = true;
            } else if (ch == 'e' || ch == 'E') {
                // we've already taken care of hex.
                if (hasExp) {
                    // two E's
                    return false;
                }
                if (!foundDigit) {
                    return false;
                }
                hasExp = true;
                allowSigns = true;
            } else if (ch == '+' || ch == '-') {
                if (!allowSigns) {
                    return false;
                }
                allowSigns = false;
                foundDigit = false; // we need a digit after the E
            } else {
                return false;
            }
            i++;
        }
        if (i < str.length()) {
            char ch = str.charAt(i);

            if (ch >= '0' && ch <= '9') {
                // no type qualifier, OK
                return true;
            }
            if (ch == 'e' || ch == 'E') {
                // can't have an E at the last byte
                return false;
            }
            if (!allowSigns
                    && (ch == 'd'
                    || ch == 'D'
                    || ch == 'f'
                    || ch == 'F')) {
                return foundDigit;
            }
            if (ch == 'l'
                    || ch == 'L') {
                // not allowing L with an exponent
                return foundDigit && !hasExp;
            }
            // last character is illegal
            return false;
        }
        // allowSigns is true iff the val ends in 'E'
        // found digit it to make sure weird stuff like '.' and '1E-' doesn't pass
        return !allowSigns && foundDigit;
    }
	
	public static String dateToStr(Date date, String format) {
		if(date==null)
			return null;
		if(format==null||format.trim().length()==0)
			format = DATETIME_FORMAT;
		
		return new SimpleDateFormat(format).format(date);
	}
	
	public static Date toDatetime(String date) {
		Date ret = null;
		SimpleDateFormat sdf = new SimpleDateFormat(DATETIME_FORMAT);
		try {
			ret = sdf.parse(date);
		}catch(Exception e) {
			
		}
		return ret;
	}

	public static Date toDatetime(String date, String format) {
		Date ret = null;
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		try {
			ret = sdf.parse(date);
		}catch(Exception e) {
			
		}
		return ret;
	}
	
	/**
	 * 自定义字符串转换为日期型
	 * 支持的格式如下：
	 * <ul>
	 * <li>yyyy.MM.dd</li>
	 * <li>yyyyMMdd</li>
	 * <li>yyyy-MM-dd</li>
	 * <li>yyyy/MM/dd</li>
	 * </ul>
	 *
	 * @author hoobort klxukun@126.com
	 * @company 北京诚朗信息技术有限公司
	 * @datetime 2022年12月11日 上午11:20:41
	 * @param date
	 * @return
	 */
	public static Date customToDate(String date) {

		//如果存在全角，先将全角转换为半角
		char[] cdate = date.toCharArray();
		String halfDate = "";
		for(int m=0; m<cdate.length; m++) {
			char c= cdate[m];
			boolean rep = false;
			for(int i=0; i<halfChars.length; i++) {
				if(c==halfChars[i][0]) {
					if(c!=' '&&c!='\u3000')
						halfDate+=halfChars[i][1];
					rep= true;
					break;
				}
			}
			if(!rep)
				halfDate+=c;
		}
		//检查是否有分隔符
		String seperator= "";
		if(halfDate.indexOf("/")>=0)
			seperator = "/";
		else if(halfDate.indexOf(".")>=0)
			seperator = "\\.";
		else if(halfDate.indexOf("-")>=0)
			seperator ="-";
		if(seperator.length()==0&&halfDate.length()!=8)
			return null;
		
		//分离日期	
		String[] ymdArray = null;
		if(seperator.length()==0) {
			if(halfDate.length()==8) {
				ymdArray = new String[3];
				ymdArray[0]= halfDate.substring(0,4);
				ymdArray[1]=halfDate.substring(4,6);
				ymdArray[2]=halfDate.substring(6);
			}else
				ymdArray=null;
			
		}else
			ymdArray = halfDate.split(seperator);
		
		if(ymdArray==null||ymdArray.length!=3)
			return null;
		else {
			Calendar c = Calendar.getInstance();
			c.set(Calendar.MILLISECOND, 0);
			c.set(Integer.parseInt(ymdArray[0]), //year
					Integer.parseInt(ymdArray[1])-1, //month
					Integer.parseInt(ymdArray[2]), //day
					0, //hour
					0, //minute
					0);//date
			return c.getTime();
		}
		
	}
	
	public static boolean emptyOrWhitespace(String source) {
		return source==null||source.trim().length()==0;
	}

	public static boolean empty(String source) {
		return source==null||source.length()==0;
	}

	public static int thisYear() {		
		return Calendar.getInstance().get(Calendar.YEAR);
	}
	
	public static int ageLimit(Date birthday) {
		if (birthday == null)
			return 0;

		Calendar c = Calendar.getInstance();
		int ny = c.get(Calendar.YEAR), nm = c.get(Calendar.MONTH), nd = c.get(Calendar.DAY_OF_MONTH);
		c.setTime(birthday);
		int oy = c.get(Calendar.YEAR), om = c.get(Calendar.MONTH), od = c.get(Calendar.DAY_OF_MONTH);

		int ret = ny - oy - 1;
		if ((nm < om) || (nm == om && nd < od)) {
			ret -= 1;
		}

		return ret<0?0:ret;
	}
	
	public static boolean isMale(String gender) {
		return "男".equals(gender);
	}

	public static boolean inArray(Integer[] array, Integer value) {
		if (array == null || array.length == 0)
			return true;

		if (value == null || value < 0)
			return false;

		boolean ret = false;
		for (int v : array) {
			ret = v == value;
			if (ret)
				break;
		}

		return ret;
	}
	
	private static final char[][] halfChars = new char[][] {
		{'\uFF10','0'},
		{'\uFF11','1'},
		{'\uFF12','2'},
		{'\uFF13','3'},
		{'\uFF14','4'},
		{'\uFF15','5'},
		{'\uFF16','6'},
		{'\uFF17','7'},
		{'\uFF18','8'},
		{'\uFF19','9'},
		{'\uFF0D','-'},
		{'\uFF0E','.'},
		{'\uFF0F','/'},
		{'\u3000',' '}
	};
	
}
